import React from 'react'
import {
  View,
  StyleSheet,
  Text,
  Image,
  TextInput,

  Keyboard,
  LayoutAnimation
} from 'react-native'
import { StackActions } from 'react-navigation'
import * as Animatable from 'react-native-animatable'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
import { ScaleS, ScaleT, IS_IPHONEX, HEIGHT, WIDTH } from 'src/utils/ScreenUtil'
import BasePage from 'src/pageP/base/base-page/index'
import CustomButton from 'src/components/button/CustomButton'
import { isEmptyObjectFn } from 'src/utils/JSTypeUtil'
import { SmsCodeReg, PhoneReg } from 'src/utils/RegUtil'
import { ShowLoading, DismissLoading } from 'src/utils/ToastUtil'
import { AgreementCustom } from 'src/config/index'
/* redux */
import { connect } from 'react-redux'
import {
  UPDATE_USERINFO_ACTION,
  DO_REQUEST_AUTH_TOKEN_ACTION,
  DO_REQUEST_USERINFO_C_ACTION,
  DO_REQUEST_USERINFO_B_ACTION
} from 'src/store/actions/userinfo'
import {
  INIT_VERIFY_CODE_LOGIN_ACTION,
  UPDATE_VERIFY_CODE_LOGIN_ACTION,
  DO_REQUEST_AUTH_SMSCODE_ACTION
} from './store/action'
import {
  DO_REQUEST_MAIN_PAGE_C_ACTION,
  DO_REQUEST_MY_CENTER_NUMBERS_ACTION
} from 'src/pageC/mine/mine-page/store/action'
import { DO_REQUEST_MAIN_PAGE_B_ACTION } from 'src/pageB/main/main-page/store/action'
import { TouchableOpacity } from 'react-native-gesture-handler'

const AnimatableTouchableOpacity = Animatable.createAnimatableComponent(
  CustomButton
)

const mapActiontoProps = dispatch => ({
  updateUserInfoState(payload) {
    dispatch({
      type: UPDATE_USERINFO_ACTION,
      payload: {
        ...payload
      }
    })
  },
  initState() {
    dispatch({
      type: INIT_VERIFY_CODE_LOGIN_ACTION
    })
  },
  updateState(payload) {
    dispatch({
      type: UPDATE_VERIFY_CODE_LOGIN_ACTION,
      payload: {
        ...payload
      }
    })
  },
  doRequestAuthSmsCode(payload) {
    const promise = DO_REQUEST_AUTH_SMSCODE_ACTION(payload)
    dispatch(promise)
    return promise.payload
  },
  doRequestAuthToken(payload) {
    const promise = DO_REQUEST_AUTH_TOKEN_ACTION(payload)
    dispatch(promise)
    return promise.payload
  },
  doRequestUserInfoC(payload) {
    const promise = DO_REQUEST_USERINFO_C_ACTION(payload)
    dispatch(promise)
    return promise.payload
  },
  doRequestUserInfoB(payload) {
    const promise = DO_REQUEST_USERINFO_B_ACTION(payload)
    dispatch(promise)
    return promise.payload
  },
  doRequestMainPageC(...payload) {
    const promise = DO_REQUEST_MAIN_PAGE_C_ACTION(...payload)
    dispatch(promise)
    return promise.payload
  },
  doRequestMyCenterNumbersC(payload) {
    const promise = DO_REQUEST_MY_CENTER_NUMBERS_ACTION(payload)
    dispatch(promise)
    return promise.payload
  },
  doRequestMainPageB(payload) {
    const promise = DO_REQUEST_MAIN_PAGE_B_ACTION(payload)
    dispatch(promise)
    return promise.payload
  }
})

@connect(
  ({ userinfo, verifyCodeLoginStore }) => ({
    userinfo,
    ...verifyCodeLoginStore
  }),
  mapActiontoProps
)
class VerifyCodeLogin extends BasePage {
  state = {
    header: {
      headerBg: 'transparent'
    }
  }

  childRender() {
    const {
      mobile,
      mobileValid,
      mobileTip,
      smsButtonText,
      smsButtonClicked,
      smsTime,
      code,
      codeTip,
      ruleChecked
    } = this.props
    const { nextButtonEnable } = this.state
    return (
      <KeyboardAwareScrollView
        contentContainerStyle={styles.container}
        enableAutomaticScroll={false}
        scrollEnabled={false}
        keyboardShouldPersistTaps="handled"
        innerRef={this.scrollRef}
        onKeyboardWillShow={this.onKeyboardWillShow}
        onKeyboardWillHide={this.onKeyboardWillHide}
      >
        <View style={styles.topImg}>
          <Image
            style={styles.logo}
            source={require('@/imgC/login/login-icon.png')}
          />
        </View>
        <Text style={styles.welcome}>登录</Text>
        <Text style={styles.title}>Sign In</Text>
        <View style={[styles.mobileBox, { marginTop: ScaleS(45) }]}>
          <View style={styles.prefixBox}>
            <Text style={styles.prefix}>+86</Text>
          </View>
          <TextInput
            style={styles.itemTextInput}
            maxLength={11}
            placeholder="输入手机号码"
            placeholderTextColor="#999999"
            value={mobile}
            keyboardType="number-pad"
            selectionColor="#FED201"
            autoFocus={false}
            onChangeText={this.mobileChanged}
          />
        </View>
        {/* <Text style={styles.mobileTip}>{mobileTip}</Text> */}
        <View style={[styles.mobileBox, styles.smsBox]}>
          <TextInput
            style={styles.itemTextInput}
            placeholder="输入验证码"
            placeholderTextColor="#999999"
            value={code}
            textContentType="oneTimeCode"
            keyboardType="number-pad"
            selectionColor="#FED201"
            onChangeText={this.smsCodeChanged}
          />
          <CustomButton onPress={this.getSmsButtonClick}>
            <Text
              style={[
                styles.smsText,
                mobileValid && smsTime === '' && styles.smsTextEnable,
                smsButtonClicked && styles.smsSended
              ]}
            >
              {smsButtonText}
            </Text>
          </CustomButton>
        </View>
        <AnimatableTouchableOpacity
          style={[styles.smsButton, nextButtonEnable && styles.smsButtonEnable]}
          transition="backgroundColor"
          // onPress={this.getSmsButtonClick}
          onPress={this.nextButtonClick}
        >
          <Animatable.Text
            style={[
              styles.smsButtonText,
              nextButtonEnable && styles.smsButtonTextEnable
            ]}
            transition="color"
          >
            验证
          </Animatable.Text>
        </AnimatableTouchableOpacity>
        <Text style={styles.mobileTip} onLayout={this.mobileTiponLayout}>{codeTip}</Text>
        <View style={styles.viewEmpty}></View>
        <View style={styles.ruleBox}>
          <AnimatableTouchableOpacity
            style={[
              styles.cc,
              styles.ruleButton,
              ruleChecked && styles.ruleButtonChecked
            ]}
            transition="backgroundColor"
            onPress={this.ruleButtonClick}
          >
            <Image style={styles.checkImg} source={require('@/imgC/login/login_check.png')} />
          </AnimatableTouchableOpacity>
          <View style={styles.rzcTextBox}>
            <Text style={[styles.rzcText, ruleChecked && styles.rzcTextChecked]}>我已阅读并同意</Text>
            <CustomButton onPress={this.userLegalClick}>
              <Text style={[styles.rzcText, ruleChecked && styles.rzcTextChecked]}>
                《人职初条款》
              </Text>
            </CustomButton>
          </View>
        </View>
      </KeyboardAwareScrollView>
    )
  }

  static getDerivedStateFromProps(props, state) {
    console.log('getDerivedStateFromProps', props)
    return VerifyCodeLogin.checkNextButtonEnable(props)
  }

  static checkNextButtonEnable(props) {
    const { mobileValid, code, ruleChecked } = props
    const nextButtonEnable = mobileValid && ruleChecked && SmsCodeReg.test(code)
    return {
      nextButtonEnable
    }
  }

  scrollRef = ref => {
    this.keyboardScroll = ref
  }

  onKeyboardWillShow = ({ endCoordinates: { height } }) => {
    if (this.mobileTipY) {
      const distance = this.mobileTipY - (HEIGHT - height) + 10
      LayoutAnimation.easeInEaseOut()
      this.keyboardScroll.setNativeProps({
        style: { marginTop: Math.min(0, -distance) }
      })
    }
  }

  onKeyboardWillHide = () => {
    LayoutAnimation.easeInEaseOut()
    this.keyboardScroll.setNativeProps({
      style: { marginTop: 0 }
    })
  }

  mobileTiponLayout = event => {
    const { height, y } = event.nativeEvent.layout
    this.mobileTipY = height + y
  }

  mobileChanged = mobile => {
    mobile = mobile || ''
    const mobileValid = PhoneReg.test(mobile)
    this.props.updateState({ mobile, mobileValid })
  }

  getSmsButtonClick = () => {
    Keyboard.dismiss()
    this.smsButtonClick().then(() => {
      this.props.updateState({
        smsButtonClicked: true
      })
    })
  }

  smsTimer = null

  smsButtonClick = () => {
    return new Promise(resolve => {
      const { mobile, mobileValid, doRequestAuthSmsCode } = this.props
      if (mobileValid && !this.smsTimer) {
        return doRequestAuthSmsCode({ mobile })
          .then(res => {
            this.handleTimer()
            resolve()
          })
          .finally(() => {
          })
      }
    })
  }

  handleTimer = () => {
    const { updateState } = this.props
    this.smsTimer = setInterval(() => {
      let { smsTime, smsButtonText } = this.props
      if (smsTime === '') {
        smsTime = 60
        smsButtonText = `已发送(${smsTime}s)`
      } else if (smsTime === 0) {
        smsTime = ''
        smsButtonText = `重新发送`
        clearInterval(this.smsTimer)
        this.smsTimer = null
      } else {
        smsTime = smsTime - 1
        smsButtonText = `已发送(${smsTime}s)`
      }
      updateState({
        smsButtonText,
        smsTime
      })
    }, 1000)
  }

  smsCodeChanged = code => {
    this.props.updateState({
      code
    })
  }

  ruleButtonClick = () => {
    const { ruleChecked } = this.props
    this.props.updateState({
      ruleChecked: !ruleChecked
    })
  }

  nextButtonClick = () => {
    Keyboard.dismiss()
    const { nextButtonEnable } = this.state
    if (nextButtonEnable) {
      const {
        mobile,
        code,
        doRequestAuthToken,
        doRequestUserInfoC,
        doRequestUserInfoB,
        doRequestMainPageC,
        doRequestMyCenterNumbersC,
        doRequestMainPageB
      } = this.props
      let params = {
        mobile,
        vcode: code,
        grant_type: 'sms_code'
      }
      this.props.updateState({
        codeTip: ''
      })
      ShowLoading()
      doRequestAuthToken({ params, headers: { noToast: true } })
        .then(res => {
          console.log('getAuthTokenRequest', res)
          const { userId } = res
          params = { userId }
          return Promise.all([
            doRequestUserInfoC({ params }),
            doRequestUserInfoB({ params })
          ])
        })
        .then(([{ C }, { B }]) => {
          const {
            userinfo: { role },
            userId
          } = this.props
          // console.log('判断用户是否存在res', C, B)
          this.LoginSuccess = true // 清空state
          if (isEmptyObjectFn(role === 'C' ? C : B)) {
            // this.props.navigation.replace(`${role}FirstUserInfo`)
            return {}
          } else {
            // this.goBack()
            if (role === 'C') {
              return Promise.all([
                doRequestMainPageC({ params }),
                doRequestMyCenterNumbersC({ type: 'C', userId })
              ])
            } else {
              return doRequestMainPageB({ userId })
            }
          }
        })
        .then(() => {
          const {
            userinfo: { role, B, C }
          } = this.props
          // console.log('判断用户是否存在res', C, B)
          this.LoginSuccess = true // 清空state
          if (isEmptyObjectFn(role === 'C' ? C : B)) {
            this.props.navigation.replace(`${role}FirstUserInfo`)
          } else {
            this.goBack()
          }
        })
        .catch(() => {
          this.props.updateState({
            codeTip: '* 验证码错误'
          })
        })
        .finally(() => {
          DismissLoading()
        })
    }
  }

  goBack = () => {
    this.props.navigation.goBack()
  }

  userLegalClick = () => {
    this.props.navigation.navigate('CommonWebView', {
      source: { uri: AgreementCustom }
    })
  }

  componentDidMount() {
    const { smsTime } = this.props
    if (!smsTime) {
      this.props.initState()
    } else {
      this.handleTimer()
    }
  }

  componentWillUnmount() {
    super.componentWillUnmount()
    this.smsTimer && clearInterval(this.smsTimer)
    this.LoginSuccess && this.props.initState()
  }
}

export default VerifyCodeLogin

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center'
  },
  cc: {
    justifyContent: 'center',
    alignItems: 'center'
  },
  topImg: {
    position: 'relative',
    width: WIDTH,
    height: ScaleS(141),
    justifyContent: 'flex-end',
    resizeMode: 'contain',
    backgroundColor: '#FFE400'
  },
  logo: {
    position: 'absolute',
    right: ScaleS(25)
  },
  welcome: {
    justifyContent: 'center',
    fontSize: ScaleT(27),
    fontWeight: '900',
    color: '#3C3C3C',
    marginTop: ScaleS(49)
  },
  title: {
    justifyContent: 'center',
    fontSize: ScaleT(12),
    color: '#444444',
    marginTop: ScaleS(6)
  },
  mobileBox: {
    width: ScaleS(262),
    height: ScaleS(55),
    borderRadius: ScaleS(28),
    borderColor: '#3C3C3C',
    borderWidth: ScaleS(1),
    borderStyle: 'solid',
    backgroundColor: '#fff',
    flexDirection: 'row',
    alignItems: 'center',
    paddingRight: ScaleS(25),
    paddingLeft: ScaleS(5),
  },
  prefixBox: {
    width: ScaleS(57),
    height: ScaleS(18),
    borderRightColor: 'rgba(151, 151, 151, .1976)',
    borderRightWidth: ScaleS(1),
    borderStyle: 'solid',
    marginRight: ScaleS(2),
    alignItems: 'center',
    justifyContent: 'center'
  },
  prefix: {
    fontSize: ScaleT(17),
    color: '#444444'
  },
  itemTextInput: {
    flex: 1,
    padding: 0,
    paddingLeft: ScaleT(15),
    color: '#3C3C3C',
    fontWeight: '500',
    fontSize: ScaleT(16),
    height: ScaleS(50),
    textAlignVertical: 'center',
    marginRight: ScaleS(15)
  },
  mobileTip: {
    fontSize: ScaleS(14),
    color: 'rgba(60,60,60,1)',
    alignSelf: 'center',
    marginTop: ScaleS(20)
  },
  smsButton: {
    marginTop: ScaleS(14),
    alignItems: 'center',
    justifyContent: 'center',
    width: ScaleS(262),
    height: ScaleS(55),
    backgroundColor: '#EEEEEE',
    borderRadius: ScaleS(28),
  },
  smsButtonEnable: {
    backgroundColor: '#000000'
  },
  smsButtonText: {
    fontSize: ScaleT(14),
    color: '#9F9F9F'
  },
  smsButtonTextEnable: {
    color: '#FFFFFF'
  },
  smsBox: {
    marginTop: ScaleS(14)
  },
  smsText: {
    textAlign: 'center',
    fontSize: ScaleT(16),
    color: '#D0D0D0'
  },
  smsTextEnable: {
    color: '#444444',
    fontWeight: '500',
    fontSize: ScaleT(16)
  },
  smsSended: {
    color: '#FFE400'
  },
  viewEmpty: {
    flex: 1
  },
  ruleBox: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    paddingBottom: IS_IPHONEX ? ScaleS(45) : ScaleS(15)
  },
  rzcTextBox: {
    flexDirection: 'row',
    justifyContent: 'space-between'
  },
  rzcText: {
    fontSize: ScaleT(12),
    fontWeight: '400',
    color: '#AAAAAA'
  },
  rzcTextChecked: {
    color: '#000'
  },
  ruleButton: {
    width: ScaleS(16),
    height: ScaleS(16),
    backgroundColor: '#EFEFEF',
    borderRadius: ScaleS(13),
    marginRight: ScaleS(5)
  },
  ruleButtonChecked: {
    backgroundColor: '#000000'
  },
  nextButton: {
    marginTop: ScaleS(21),
    alignSelf: 'flex-end',
    width: ScaleS(70),
    height: ScaleS(70),
    backgroundColor: 'rgba(255, 216, 16, 0.3)',
    borderRadius: ScaleS(35)
  },
  nextButtonEnable: {
    backgroundColor: 'rgba(255, 216, 16, 1)'
  },
  checkImg: {
    width: ScaleS(9),
    height: ScaleS(9)
  }
})
